home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / mint / utilit~1 / futilsrc.zoo / fileutil / src / rm.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-21  |  11.9 KB  |  490 lines

  1. /* `rm' file deletion utility for GNU.
  2.    Copyright (C) 1988-1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Paul Rubin, David MacKenzie, and Richard Stallman. */
  19.  
  20. #include <stdio.h>
  21. #include <getopt.h>
  22. #include <sys/types.h>
  23. #include "system.h"
  24.  
  25. #ifdef _POSIX_SOURCE
  26. /* POSIX.1 doesn't have inodes, so fake them to avoid lots of ifdefs. */
  27. #define ino_t unsigned long
  28. #define D_INO(dp) 1
  29. #else
  30. #define D_INO(dp) ((dp)->d_ino)
  31. #endif
  32.  
  33. char *basename ();
  34. char *stpcpy ();
  35. char *xmalloc ();
  36. char *xrealloc ();
  37. int clear_directory ();
  38. int duplicate_entry ();
  39. int eaccess_stat ();
  40. int remove_dir ();
  41. int remove_file ();
  42. int rm ();
  43. int yesno ();
  44. void error ();
  45. void strip_trailing_slashes ();
  46. void usage ();
  47.  
  48. /* Path of file now being processed; extended as necessary. */
  49. char *pathname;
  50.  
  51. /* Number of bytes currently allocated for `pathname';
  52.    made larger when necessary, but never smaller.  */
  53. int pnsize;
  54.  
  55. /* Name this program was run with.  */
  56. char *program_name;
  57.  
  58. /* If nonzero, display the name of each file removed. */
  59. int verbose;
  60.  
  61. /* If nonzero, ignore nonexistant files. */
  62. int ignore_missing_files;
  63.  
  64. /* If nonzero, recursively remove directories. */
  65. int recursive;
  66.  
  67. /* If nonzero, query the user about whether to remove each file. */
  68. int interactive;
  69.  
  70. /* If nonzero, remove directories with unlink instead of rmdir, and don't
  71.    require a directory to be empty before trying to unlink it.
  72.    Only works for the super-user. */
  73. int unlink_dirs;
  74.  
  75. /* If nonzero, stdin is a tty. */
  76. int stdin_tty;
  77.  
  78. struct option long_opts[] =
  79. {
  80.   {"directory", 0, &unlink_dirs, 1},
  81.   {"force", 0, NULL, 'f'},
  82.   {"interactive", 0, NULL, 'i'},
  83.   {"recursive", 0, &recursive, 1},
  84.   {"verbose", 0, &verbose, 1},
  85.   {NULL, 0, NULL, 0}
  86. };
  87.  
  88. void
  89. main (argc, argv)
  90.      int argc;
  91.      char **argv;
  92. {
  93.   int err = 0;
  94.   int c;
  95.  
  96.   verbose = ignore_missing_files = recursive = interactive
  97.     = unlink_dirs = 0;
  98.   pnsize = 256;
  99.   pathname = xmalloc (pnsize);
  100.   program_name = argv[0];
  101.  
  102.   while ((c = getopt_long (argc, argv, "dfirvR", long_opts, (int *) 0)) != EOF)
  103.     {
  104.       switch (c)
  105.     {
  106.     case 0:        /* Long option. */
  107.       break;
  108.     case 'd':
  109.       unlink_dirs = 1;
  110.       break;
  111.     case 'f':
  112.       interactive = 0;
  113.       ignore_missing_files = 1;
  114.       break;
  115.     case 'i':
  116.       interactive = 1;
  117.       ignore_missing_files = 0;
  118.       break;
  119.     case 'r':
  120.     case 'R':
  121.       recursive = 1;
  122.       break;
  123.     case 'v':
  124.       verbose = 1;
  125.       break;
  126.     default:
  127.       usage ();
  128.     }
  129.     }
  130.  
  131.   if (optind == argc)
  132.     usage ();
  133.  
  134.   stdin_tty = isatty (0);
  135.  
  136.   for (; optind < argc; optind++)
  137.     {
  138.       int len;
  139.  
  140.       strip_trailing_slashes (argv[optind]);
  141.       len = strlen (argv[optind]);
  142.       if (len + 1 > pnsize)
  143.     {
  144.       free (pathname);
  145.       pnsize = 2 * (len + 1);
  146.       pathname = xmalloc (pnsize);
  147.     }
  148.       strcpy (pathname, argv[optind]);
  149.       err += rm ();
  150.     }
  151.  
  152.   exit (err > 0);
  153. }
  154.  
  155. /* Remove file or directory `pathname' after checking appropriate things.
  156.    Return 0 if `pathname' is removed, 1 if not. */
  157.  
  158. int
  159. rm ()
  160. {
  161.   struct stat path_stats;
  162.   char *base = basename (pathname);
  163.  
  164.   if (base[0] == '.' && (base[1] == '\0'
  165.                  || (base[1] == '.' && base[2] == '\0')))
  166.     {
  167.       error (0, 0, "cannot remove `.' or `..'");
  168.       return 1;
  169.     }
  170.  
  171.   if (lstat (pathname, &path_stats))
  172.     {
  173.       if (errno == ENOENT && ignore_missing_files)
  174.     return 0;
  175.       error (0, errno, "%s", pathname);
  176.       return 1;
  177.     }
  178.  
  179.   if (S_ISDIR (path_stats.st_mode) && !unlink_dirs)
  180.     return remove_dir (&path_stats);
  181.   else
  182.     return remove_file (&path_stats);
  183. }
  184.  
  185. /* Query the user if appropriate, and if ok try to remove the
  186.    non-directory `pathname', which STATP contains info about.
  187.    Return 0 if `pathname' is removed, 1 if not. */
  188.  
  189. int
  190. remove_file (statp)
  191.      struct stat *statp;
  192. {
  193.   if (!ignore_missing_files && (interactive || stdin_tty)
  194.       && eaccess_stat (statp, W_OK))
  195.     {
  196.       fprintf (stderr, "%s: remove %s`%s', overriding mode %04o? ",
  197.            program_name,
  198.            S_ISDIR (statp->st_mode) ? "directory " : "",
  199.            pathname,
  200.            statp->st_mode & 07777);
  201.       if (!yesno ())
  202.     return 1;
  203.     }
  204.   else if (interactive)
  205.     {
  206.       fprintf (stderr, "%s: remove %s`%s'? ", program_name,
  207.            S_ISDIR (statp->st_mode) ? "directory " : "",
  208.            pathname);
  209.       if (!yesno ())
  210.     return 1;
  211.     }
  212.  
  213.   if (verbose)
  214.     printf ("%s\n", pathname);
  215.  
  216.   if (unlink (pathname))
  217.     {
  218.       error (0, errno, "%s", pathname);
  219.       return 1;
  220.     }
  221.   return 0;
  222. }
  223.  
  224. /* If not in recursive mode, print an error message and return 1.
  225.    Otherwise, query the user if appropriate, then try to recursively
  226.    remove directory `pathname', which STATP contains info about.
  227.    Return 0 if `pathname' is removed, 1 if not. */
  228.  
  229. int
  230. remove_dir (statp)
  231.      struct stat *statp;
  232. {
  233.   int err;
  234.  
  235.   if (!recursive)
  236.     {
  237.       error (0, 0, "%s: is a directory", pathname);
  238.       return 1;
  239.     }
  240.  
  241.   if (!ignore_missing_files && (interactive || stdin_tty)
  242.       && eaccess_stat (statp, W_OK))
  243.     {
  244.       fprintf (stderr,
  245.            "%s: descend directory `%s', overriding mode %04o? ",
  246.            program_name, pathname, statp->st_mode & 07777);
  247.       if (!yesno ())
  248.     return 1;
  249.     }
  250.   else if (interactive)
  251.     {
  252.       fprintf (stderr, "%s: descend directory `%s'? ",
  253.            program_name, pathname);
  254.       if (!yesno ())
  255.     return 1;
  256.     }
  257.  
  258.   if (verbose)
  259.     printf ("%s\n", pathname);
  260.  
  261.   err = clear_directory (statp);
  262.  
  263.   if (interactive)
  264.     {
  265.       if (err)
  266.     fprintf (stderr, "%s: remove directory `%s' (might be nonempty)? ",
  267.          program_name, pathname);
  268.       else
  269.     fprintf (stderr, "%s: remove directory `%s'? ",
  270.          program_name, pathname);
  271.       if (!yesno ())
  272.     return 1;
  273.     }
  274.  
  275.   if (rmdir (pathname))
  276.     {
  277.       error (0, errno, "%s", pathname);
  278.       return 1;
  279.     }
  280.   return 0;
  281. }
  282.  
  283. /* An element in a stack of pointers into `pathname'.
  284.    `pathp' points to where in `pathname' the terminating '\0' goes
  285.    for this level's directory name. */
  286. struct pathstack
  287. {
  288.   struct pathstack *next;
  289.   char *pathp;
  290.   ino_t inum;
  291. };
  292.  
  293. /* Linked list of pathnames of directories in progress in recursive rm.
  294.    The entries actually contain pointers into `pathname'.
  295.    `pathstack' is the current deepest level. */
  296. static struct pathstack *pathstack = NULL;
  297.  
  298. /* Read directory `pathname' and remove all of its entries,
  299.    avoiding use of chdir.
  300.    On entry, STATP points to the results of stat on `pathname'.
  301.    Return 0 for success, error count for failure.
  302.    Upon return, `pathname' will have the same contents as before,
  303.    but its address might be different; in that case, `pnsize' will
  304.    be larger, as well. */
  305.  
  306. int
  307. clear_directory (statp)
  308.      struct stat *statp;
  309. {
  310.   DIR *dirp;
  311.   struct direct *dp;
  312.   char *name_space;        /* Copy of directory's filenames. */
  313.   char *namep;            /* Current entry in `name_space'. */
  314.   unsigned name_size;        /* Bytes allocated for `name_space'. */
  315.   int name_length;        /* Length of filename in `namep' plus '\0'. */
  316.   int pathname_length;        /* Length of `pathname'. */
  317.   ino_t *inode_space;        /* Copy of directory's inodes. */
  318.   ino_t *inodep;        /* Current entry in `inode_space'. */
  319.   unsigned inode_size;        /* Bytes allocated for `inode_space'. */
  320.   int err = 0;            /* Return status. */
  321.   struct pathstack pathframe;    /* New top of stack. */
  322.   struct pathstack *pp;        /* Temporary. */
  323.  
  324.   name_size = statp->st_size;
  325.   name_space = (char *) xmalloc (name_size);
  326.  
  327.   inode_size = statp->st_size;
  328.   inode_space = (ino_t *) xmalloc (inode_size);
  329.  
  330.   do
  331.     {
  332.       namep = name_space;
  333.       inodep = inode_space;
  334.  
  335.       errno = 0;
  336.       dirp = opendir (pathname);
  337.       if (dirp == NULL)
  338.     {
  339.       error (0, errno, "%s", pathname);
  340.       free (name_space);
  341.       free (inode_space);
  342.       return 1;
  343.     }
  344.  
  345.       while ((dp = readdir (dirp)) != NULL)
  346.     {
  347.       /* Skip "." and ".." (some NFS filesystems' directories lack them). */
  348.       if (dp->d_name[0] != '.'
  349.           || (dp->d_name[1] != '\0'
  350.           && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
  351.         {
  352.           unsigned size_needed = (namep - name_space) + NLENGTH (dp) + 2;
  353.  
  354.           if (size_needed > name_size)
  355.         {
  356.           char *new_name_space;
  357.  
  358.           while (size_needed > name_size)
  359.             name_size += 1024;
  360.  
  361.           new_name_space = xrealloc (name_space, name_size);
  362.           namep += new_name_space - name_space;
  363.           name_space = new_name_space;
  364.         }
  365.           namep = stpcpy (namep, dp->d_name) + 1;
  366.  
  367.           if (inodep == inode_space + inode_size)
  368.         {
  369.           ino_t *new_inode_space;
  370.  
  371.           inode_size += 1024;
  372.           new_inode_space = (ino_t *) xrealloc (inode_space, inode_size);
  373.           inodep += new_inode_space - inode_space;
  374.           inode_space = new_inode_space;
  375.         }
  376.           *inodep++ = D_INO (dp);
  377.         }
  378.     }
  379.       *namep = '\0';
  380.       if (CLOSEDIR (dirp))
  381.     {
  382.       error (0, errno, "%s", pathname);
  383.       err = 1;
  384.     }
  385.  
  386.       pathname_length = strlen (pathname);
  387.  
  388.       for (namep = name_space, inodep = inode_space; *namep != '\0';
  389.        namep += name_length, inodep++)
  390.     {
  391.       name_length = strlen (namep) + 1;
  392.  
  393.       /* Satisfy GNU requirement that filenames can be arbitrarily long. */
  394.       if (pathname_length + 1 + name_length > pnsize)
  395.         {
  396.           char *new_pathname;
  397.  
  398.           pnsize = (pathname_length + 1 + name_length) * 2;
  399.           new_pathname = xrealloc (pathname, pnsize);
  400.           /* Update the all the pointers in the stack to use the new area. */
  401.           for (pp = pathstack; pp != NULL; pp = pp->next)
  402.         pp->pathp += new_pathname - pathname;
  403.           pathname = new_pathname;
  404.         }
  405.  
  406.       /* Add a new frame to the top of the path stack. */
  407.       pathframe.pathp = pathname + pathname_length;
  408.       pathframe.inum = *inodep;
  409.       pathframe.next = pathstack;
  410.       pathstack = &pathframe;
  411.  
  412.       /* Append '/' and the filename to current pathname, take care of the
  413.          file (which could result in recursive calls), and take the filename
  414.          back off. */
  415.  
  416.       *pathstack->pathp = '/';
  417.       strcpy (pathstack->pathp + 1, namep);
  418.  
  419.       /* If the i-number has already appeared, there's an error. */
  420.       if (duplicate_entry (pathstack->next, pathstack->inum))
  421.         err++;
  422.       else if (rm ())
  423.         err++;
  424.  
  425.       *pathstack->pathp = '\0';
  426.       pathstack = pathstack->next;    /* Pop the stack. */
  427.     }
  428.     }
  429.   /* Keep trying while there are still files to remove. */
  430.   while (namep > name_space && err == 0);
  431.  
  432.   free (name_space);
  433.   free (inode_space);
  434.   return err;
  435. }
  436.  
  437. /* If STACK does not already have an entry with the same i-number as INUM,
  438.    return 0. Otherwise, ask the user whether to continue;
  439.    if yes, return 1, and if no, exit.
  440.    This assumes that no one tries to remove filesystem mount points;
  441.    doing so could cause duplication of i-numbers that would not indicate
  442.    a corrupted file system. */
  443.  
  444. int
  445. duplicate_entry (stack, inum)
  446.      struct pathstack *stack;
  447.      ino_t inum;
  448. {
  449. #ifndef _POSIX_SOURCE
  450.   struct pathstack *p;
  451.  
  452.   for (p = stack; p != NULL; p = p->next)
  453.     {
  454.       if (p->inum == inum)
  455.     {
  456.       fprintf (stderr, "\
  457. %s: WARNING: Circular directory structure.\n\
  458. This almost certainly means that you have a corrupted file system.\n\
  459. NOTIFY YOUR SYSTEM MANAGER.\n\
  460. Cycle detected:\n\
  461. %s\n\
  462. is the same file as\n", program_name, pathname);
  463.       *p->pathp = '\0';    /* Truncate pathname. */
  464.       fprintf (stderr, "%s\n", pathname);
  465.       *p->pathp = '/';    /* Put it back. */
  466.       if (interactive)
  467.         {
  468.           fprintf (stderr, "%s: continue? ", program_name);
  469.           if (!yesno ())
  470.         exit (1);
  471.           return 1;
  472.         }
  473.       else
  474.         exit (1);
  475.     }
  476.     }
  477. #endif
  478.   return 0;
  479. }
  480.  
  481. void
  482. usage ()
  483. {
  484.   fprintf (stderr, "\
  485. Usage: %s [-dfirvR] [+directory] [+force] [+interactive] [+recursive]\n\
  486.        [+verbose] path...\n",
  487.        program_name);
  488.   exit (1);
  489. }
  490.